package com.yc.javaee.多线程;

public class 同步代码 {

    public static void main(String[] args) {

        A a = new A();

        new Thread(()->{
            try {
                a.play();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                a.eat();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                a.singe();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                a.study();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // 当一个线程进入同步块( 获得同步锁 )
        // 他线程不能进入任何一个被锁定的代码块
        // 前提是: 这些同步块必须是锁定相同对象
    }

}

class A {

    // 同步方法
    // 实例方法: 锁定当前对象  this
    // 静态方法: 锁定当前类 class
    synchronized void play() throws InterruptedException {
        System.out.println("开始玩游戏");
        Thread.sleep(1000);
        System.out.println("玩完了");
    }

    synchronized void eat() throws InterruptedException {
        System.out.println("开始吃东西");
        Thread.sleep(1000);
        System.out.println("吃完了");
    }

    void singe() throws InterruptedException {
        System.out.println("先练练嗓子");
        synchronized( this ) {
            System.out.println("开始唱歌");
            Thread.sleep(1000);
            System.out.println("唱完了");
        }
    }

    Object lock = new Object();
    void study() throws InterruptedException {
        System.out.println("准备学习");
        synchronized( lock ) {
            System.out.println("开始学习");
            Thread.sleep(1000);
            System.out.println("学完了");
        }
    }



}
